<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>写文章</title>

        <link rel="stylesheet" href="/static/admin/component/elementui/index.min.css">
        <link rel="stylesheet" href="/static/admin/component/toastui-editor/toastui-editor.min.css">
        <style>
            .elform-editor .el-form-item__content {
                margin-left: 0 !important;
            }
        </style>
    </head>

    <body>
        <div class="pear-container">
            <div class="layui-card">
                <div id="app" class="layui-card-body">

                    <!-- elementui表单 -->
                    <el-form ref="articleForm" :model="articleForm" :rules="articleFormRules" label-width="80px" style="margin: 15px 10px;">
                        <!-- 文章标题 -->
                        <el-form-item label="文章标题" prop="title">
                            <el-input v-model="articleForm.title" clearable></el-input>
                        </el-form-item>
                        <!-- 文章分类 -->
                        <el-form-item label="文章分类" prop="cate_name">
                            <el-select v-model="articleForm.cate_name" clearable placeholder="请选择分类">
                                <el-option v-for="cate in cateList" :key="cate.id" :label="cate.name" :value="cate.name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- 文章描述 -->
                        <el-form-item label="文章描述" prop="description">
                            <el-input type="textarea" :rows="2" v-model="articleForm.description" clearable></el-input>
                        </el-form-item>
                        <!-- 是否置顶 -->
                        <el-form-item label="是否置顶" prop="istop">
                            <el-switch v-model="articleForm.istop" :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                        <!-- 文章内容 -->
                        <el-form-item class="elform-editor" :label-width="0">
                            <div id="editor"></div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" size="small" @click="publishArticle()">发布</el-button>
                            <el-button size="small" @click="resetForm()">重置</el-button>
                        </el-form-item>
                    </el-form>


                </div>
            </div>
        </div>

        <script src="/static/admin/component/elementui/vue.min.js"></script>
        <script src="/static/admin/component/elementui/index.min.js"></script>
        <script src="/static/admin/component/toastui-editor/toastui-editor-all.min.js"></script>
        <script src="/static/admin/component/toastui-editor/zh-cn.js"></script>
        <script type="text/javascript">
            // 获取当前时间字符串
            function getNowTimeStr() {
                let now = new Date();
                let year = now.getFullYear();
                let month = now.getMonth() + 1;
                let day = now.getDate();
                let hour = now.getHours();
                let minute = now.getMinutes();
                let second = now.getSeconds();

                let datetimeStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                return datetimeStr;
            }
        </script>

        <script type="text/javascript">
            new Vue({
                el: '#app',
                data: {
                    // markdown编辑器实例
                    editor: null,
                    // 分类列表
                    cateList: [],
                    // 添加文章表单
                    articleForm: {
                        title: '',
                        cate_name: '',
                        description: '',
                        content: '',
                        istop: 0,
                        created_at: '',
                        updated_at: '',
                    },
                    // 添加文章表单验证规则
                    articleFormRules: {
                        title: [
                            { required: true, message: '请输入文章标题', trigger: 'blur' },
                        ],
                        cate_name: [
                            { required: true, message: '请选择分类', trigger: 'change' }
                        ],
                        description: [
                            { required: true, message: '请输入文章描述', trigger: 'blur' }
                        ],
                    },
                },
                mounted() {
                    // 获取分类列表
                    fetch("/cate/list", {
                        method: "GET",
                        headers: {
                            "Accept": "application/json",
                            "Authorization": sessionStorage.getItem('token') || '',
                        },
                    })
                        .then((response) => response.json())
                        .then(res => {
                            if (res.code != 200) {
                                return this.$message.error('获取数据失败');
                            }

                            this.cateList = res.data;
                        })
                        .catch((err) => {
                            console.error("Error:", err);
                        });

                    // 创建编辑器
                    this.editor = new toastui.Editor({
                        el: document.querySelector('#editor'),
                        height: '560px',
                        language: 'zh-CN',  // 设置语言为中文
                        initialEditType: 'markdown',    // 设置编辑器初始模式为Markdown
                        previewStyle: 'vertical',   // 设置预览样式为垂直
                        usageStatistics: false, // 禁用统计数据
                        previewHighlight: true, // 启用高亮
                    });

                },
                methods: {
                    // 发布文章
                    publishArticle() {
                        // 表单验证
                        this.$refs.articleForm.validate(valid => {
                            if (!valid) {   // 表单验证不通过
                                return this.$message.warning('请检查表单是否填写完整！');
                            }
                            if (this.editor.getMarkdown() == '') {
                                return this.$message.warning('文章内容不能为空！');
                            }

                            this.articleForm.content = this.editor.getMarkdown();
                            this.articleForm.created_at = getNowTimeStr();
                            this.articleForm.updated_at = getNowTimeStr();

                            fetch("/admin/article/write", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json;charset=UTF-8",
                                    "Authorization": sessionStorage.getItem('token') || '',
                                },
                                body: JSON.stringify(this.articleForm),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error('操作失败！');
                                    }

                                    this.$message.success('操作成功！');
                                    this.resetForm();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });

                        });
                    },

                    // 重置表单
                    resetForm() {
                        this.$refs.articleForm.resetFields();
                        // 清空编辑器内容
                        this.editor.setMarkdown('');
                        this.editor.setHTML('');
                        this.articleForm.content = '';
                    },
                }
                
            });

        </script>

    </body>

</html>